package com.primaryedu.ui.center;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.AccountBean;
import com.primaryedu.data.Config;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.PhotosDialog;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.ImageUtil;
import com.primaryedu.utils.UploadUtil;
import com.primaryedu.utils.UploadUtil.OnUploadProcessListener;
import com.primaryedu.widget.CircularImage;
import com.primaryedu.widget.PopDateHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;


/**
 * 个人信息
 *
 * @author jun.wang
 * @description
 * @data 2016年12月14日
 */
public class PersonalActivity extends BaseActivity implements OnClickListener, OnUploadProcessListener {
    private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private String imagePath = "";
    private File tempFile;
    private Bitmap bitmap;

    private TextView text_name, text_gender, text_phone;
    private CircularImage headImage;
//    LoadImage loadImage;
    PopDateHelper popDateHelper;
    private PhotosDialog.Builder Builder;
    Dialog dialog;
    LayoutInflater inflater;

    private String picpath1 = "";

    /**
     * 去上传文件
     */
    protected static final int TO_UPLOAD_FILE = 1;
    /**
     * 上传文件响应
     */
    protected static final int UPLOAD_FILE_DONE = 2; //
    /**
     * 选择文件
     */
    public static final int TO_SELECT_PHOTO = 3;
    /**
     * 上传初始化
     */
    private static final int UPLOAD_INIT_PROCESS = 4;
    /**
     * 上传中
     */
    private static final int UPLOAD_IN_PROCESS = 5;
    /***
     * 这里的这个URL是我服务器的javaEE环境URL
     */
    private static String requestURL = Contants.course_api + "/rest/upload/image";


    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    setData();
                    break;

                case UPLOAD_FILE_DONE:
                    String jsonStr = msg.obj.toString();
                    System.out.println("json===" + jsonStr);

                    try {
                        JSONObject json = new JSONObject(jsonStr);
                        int result = json.getInt("result");
                        String reason = json.getString("reason");

                        if (result == 1) {
                            String data = json.getString("data");
                            JSONObject listObj = new JSONObject(data);
                            picpath1 = listObj.getString("picpath1");
                            Log.i("yy", "handleMessage: pic" + picpath1);
                            String webServerUrl = listObj.getString("webServerUrl");

                            if (!TextUtils.isEmpty(picpath1)) {
                                uplatePersonInfo();
                            }

                        } else {
                            showToast(reason);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                default:
                    break;
            }
        }

        ;
    };
    private AccountBean bean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_personal);

    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText("个人信息");
        findViewById(R.id.text_modification).setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        text_name = (TextView) this.findViewById(R.id.text_name);
//		text_gender = (TextView)this.findViewById(R.id.text_gender) ;
        text_phone = (TextView) this.findViewById(R.id.text_phone);
        text_phone.setOnClickListener(this);
        headImage = (CircularImage) this.findViewById(R.id.headImage);
        headImage.setOnClickListener(this);
//        loadImage = LoadImage.getInstance();
        inflater = LayoutInflater.from(this);
    }

    @Override
    protected void initData() {
        requestData();
    }

    @Override
    protected void onResume() {
        super.onResume();

//		requestData() ;
    }

    private void setData() {
        Glide.with(PersonalActivity.this)
                .load(bean.getData().getPhotourl())
                .placeholder(R.drawable.head_nan)
                .error(R.drawable.head_nan)
                .centerCrop()
                .crossFade()
                .into(headImage);
//		headImage.setTag(bean.getData().getPhotourl());
//		loadImage.addTask(bean.getData().getPhotourl(), headImage);
//		loadImage.doTask();
        text_name.setText(bean.getData().getName());
//		text_gender.setText(bean.getData().getSex());
        text_phone.setText(bean.getData().getMobile());

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.text_modification:
                intent = new Intent(PersonalActivity.this, PasswordModActivity.class);
                startActivity(intent);
                break;

            case R.id.back:
                finish();
                break;

            case R.id.text_phone:
                intent = new Intent(PersonalActivity.this, ModPhoneActivity.class);
                startActivity(intent);
                finish();
                break;

            case R.id.headImage:
                showPhoto();
                break;

            default:
                break;
        }
    }

    private void requestData() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getAccount);
        builder.append("?userid=" + GlobalData.getUserId(PersonalActivity.this));

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {

                try {
                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");
                    Log.e("yy", "data: ========" + data);
                    if (result == 1) {

                        bean = new Gson().fromJson(arg0,
                                new TypeToken<AccountBean>() {
                                }.getType());
                        System.out.println("bean==" + bean.toString());
                        GlobalData.accountBean = bean;
                        handler.sendEmptyMessage(1001);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
//	            showToast(ErrorMsg.net_error) ;
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

    private void requestHead() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.uploadHeadimg);
        builder.append("?userid=" + GlobalData.getUserId(PersonalActivity.this));

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {

                try {
                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");

                    if (result == 1) {

                        AccountBean bean = new Gson().fromJson(data,
                                new TypeToken<AccountBean>() {
                                }.getType());
                        System.out.println("bean==" + bean);
                        GlobalData.accountBean = bean;
                        handler.sendEmptyMessage(1001);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
//	            showToast(ErrorMsg.net_error) ;
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

    private void showPhoto() {
        Builder = new PhotosDialog.Builder(PersonalActivity.this);
        dialog = Builder.create();
        View view = inflater.inflate(R.layout.dialog_photo, null);

        view.findViewById(R.id.image_take).setOnClickListener(this);
        view.findViewById(R.id.image_video).setOnClickListener(this);

        // 相册
        view.findViewById(R.id.image_video).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

                Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                getImage.setType("image/*");
                startActivityForResult(getImage, PHOTO_REQUEST_GALLERY);
            }
        });

        // 拍照
        view.findViewById(R.id.image_take).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                // 判断存储卡是否可以用，可用进行存储
                if (hasSdcard()) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(Environment
                                    .getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                }

                startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
            }
        });

        dialog.addContentView(view, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();       //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 1.0);    //宽度设置为屏幕的0.9
        p.height = (int) (d.getHeight() * 0.5);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.setCanceledOnTouchOutside(true);
    }

    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (hasSdcard()) {
                tempFile = new File(Environment.getExternalStorageDirectory(),
                        PHOTO_FILE_NAME);
                crop(Uri.fromFile(tempFile));

            } else {
                Toast.makeText(PersonalActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG)
                        .show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                bitmap = data.getParcelableExtra("data");
                Log.i("yy", "onActivityResult: bitmap======" + bitmap);
                this.headImage.setImageBitmap(bitmap);
                Log.i("yy", "onActivityResult: " + bitmap.toString());
                //图片上传
//				uploadimage();
//				getBitmapByte(bitmap);
                Log.i("yy", "onActivityResult:er jin zhi====== " + getBitmapByte(bitmap));
                // 删除临时文件
                ImageUtil.saveToSdcard(bitmap);
                imagePath = Config.SDPATH_HEAD + "temp_photo.jpg";

                // 替换服务器上面的头像
                toUploadFile();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    private void uploadimage() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.uploadImage);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, builder.toString(),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("updateHeading==" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");

                            if (result == 1) {
                                showToast(reason);
                            } else {
                                showToast(reason);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("moduleName", "");
                map.put("pic", String.valueOf((bitmap)));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2015-04-15
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void toUploadFile() {
//		Map<String, String> params = new HashMap<>();
//		        params.put("moduleName", "headImage");
//		        params.put("pic", new File(bitmap));
//		Map<String, String> headers = new HashMap<>();
//		headers.put("Content-Type", "multipart/form-data");
//
//
//		String url = "http://www.47.104.57.2:8080/rest/upload/image";
//
//		OkHttpUtils.post()//
//				.url(url)//
//				.params(params)//
//				.headers(headers)//
//				.build()//
//				.execute(new StringCallback() {
//					@Override
//					public void onError(Call call, Exception e, int id) {
//
//					}
//
//					@Override
//					public void onResponse(String response, int id) {
//						System.out.println("updateHeadImage=="+response);
//					}
//				});


        String fileKey = "pic";   // 服务器与客户端协调好的key值或叫name值
        UploadUtil uploadUtil = UploadUtil.getInstance();
        uploadUtil.setOnUploadProcessListener(this); // 设置监听器监听上传状态

//		Map<String, String> params = new HashMap<String, String>();
//		params.put("userid",GlobalData.accountBean.getId());

        uploadUtil.uploadFile(Config.SDPATH_HEAD + "temp_photo.jpg", fileKey,
                requestURL, null);
    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
        handler.sendMessage(msg);
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        handler.sendMessage(msg);
    }

    @Override
    public void initUpload(int fileSize) {
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        handler.sendMessage(msg);
    }

    private void uplatePersonInfo() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.updateHeading,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("updateHeading==" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");

                            if (result == 1) {
                                showToast(reason);
                                Intent intent = new Intent();
                                setResult(3, intent);
                            } else {
                                showToast(reason);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("userid", GlobalData.getUserId(PersonalActivity.this));
                map.put("imgUrl", picpath1);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

}
